<script setup lang="ts">
import { h, nextTick } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Modal, Image, Dropdown, Menu } from 'ant-design-vue'
import {  ReloadOutlined, DownloadOutlined, CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import type { PaginationProps, TableProps } from 'ant-design-vue'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import type { RegistrationItem, ExamSubject } from '~/api/common/login'
import { getRegistrationListApi, updateRegistrationStatusApi, batchApproveRegistrationApi, exportLibfRegistrationsApi, getSubjectsApi } from '~/api/common/login'

defineOptions({
  name: 'TableList',
  components: {
    Dropdown,
    Menu,
  },
})

type TableRow = RegistrationItem & {
  key: number
}

// 状态映射函数
function getRegistrationStatusText(status: number): string {
  const statusMap: Record<number, string> = {
    0: '信息待完善',
    1: '待缴费',
    2: '缴费待审核',
    3: '缴费待审核（已申请开发票）',
    4: '已缴费成功（不申请发票）',
    5: '已缴费成功（申请发票 发票审核中）',
    6: '已缴费成功（申请发票 发票已开）',
    7: '缴费审核拒绝（未申请开发票）',
    8: '缴费审核拒绝（已申请开发票 发票未开票失败）',
  }
  return statusMap[status] || '未知状态'
}

// 获取报名类型（首次/补考）
function getRegistrationType(item: RegistrationItem): string {
  // 根据makeup_unit字段判断：如果有makeup_unit且不为空，则是补考；否则是首次
  if (item.makeup_unit && item.makeup_unit.trim() !== '' && item.makeup_unit !== '[]') {
    return '补考'
  }
  return '首次'
}

// 获取考试科目显示名称（包含补考/首次标识）
function getSubjectDisplayName(item: RegistrationItem): string {
  const subjectName = item.exam_subject?.subject_name || ''
  // 去掉"首次报名"、"补考报名"等后缀
  const cleanName = subjectName
    .replace(/\s*首次报名\s*/g, '')
    .replace(/\s*补考报名\s*/g, '')
    .replace(/\s*首次\s*/g, '')
    .replace(/\s*补考\s*/g, '')
    .trim() || subjectName
  
  // 根据makeup_unit判断是补考还是首次
  const registrationType = getRegistrationType(item)
  if (registrationType === '补考') {
    return `补考 ${cleanName}`
  }
  return `首次报名 ${cleanName}`
}

// 获取正确的费用
function getCorrectFee(item: RegistrationItem): string {
  const registrationType = getRegistrationType(item)
  if (registrationType === '补考') {
    // 补考：根据makeup_unit判断是一个单元还是两个单元
    const makeupUnit = item.makeup_unit
    if (makeupUnit === '[1]' || makeupUnit === '[2]') {
      // 一个单元
      return item.exam_subject?.single_unit_fee || '0.00'
    } else if (makeupUnit === '[1,2]' || makeupUnit === '[2,1]') {
      // 两个单元
      return item.exam_subject?.two_unit_fee || '0.00'
    }
    // 默认返回single_unit_fee
    return item.exam_subject?.single_unit_fee || '0.00'
  }
  // 首次报名：返回exam_fee
  return item.exam_fee || item.exam_subject?.exam_fee || '0.00'
}

// 获取报考单元文本
function getExamUnitText(makeupUnit: string | null | undefined): string {
  if (!makeupUnit || makeupUnit.trim() === '' || makeupUnit === '[]') {
    return ''
  }
  if (makeupUnit === '[1]') {
    return '跟单信用证基础 (FODC)'
  }
  if (makeupUnit === '[2]') {
    return '跟单信用证管理 (MGDC)'
  }
  if (makeupUnit === '[1,2]' || makeupUnit === '[2,1]') {
    return '跟单信用证基础 (FODC),跟单信用证管理 (MGDC)'
  }
  return makeupUnit
}

// 处理支付凭证图片（支持多张图片）
function getPaymentProofImages(paymentProof: string | string[] | null | undefined): string[] {
  if (!paymentProof) {
    return []
  }
  
  // 如果是数组，直接返回
  if (Array.isArray(paymentProof)) {
    return paymentProof.filter(img => img && img.trim())
  }
  
  // 如果是字符串，尝试按逗号、分号或换行符分割
  if (typeof paymentProof === 'string') {
    const images = paymentProof
      .split(/[,;\n\r]+/)
      .map(img => img.trim())
      .filter(img => img && img.length > 0)
    return images
  }
  
  return []
}

function getPaymentStatusText(status: number | null | undefined): string {
  const map: Record<number, string> = {
    0: '未支付',
    2: '已支付',
    3: '已支付',
    4: '已支付',
    5: '已支付',
    1: '未支付',
  }
  if (status === null || status === undefined) {
    return '未知'
  }
  return map[status] || '未知'
}

const columns = shallowRef([
  { title: '姓名', dataIndex: 'username', width: 100, fixed: 'left' as const, align: 'center' as const },
  { title: '性别', dataIndex: 'gender', 
  fixed: 'left' as const,
  width: 70, align: 'center' as const },
  { title: '考试科目', dataIndex: 'exam_subject',fixed: 'left' as const, width: 250, align: 'center' as const },
  { title: '费用', dataIndex: 'fee', width: 120, fixed: 'right' as const, align: 'center' as const },
  { title: '支付凭证', dataIndex: 'payment_proof', width: 150, fixed: 'right' as const, align: 'center' as const },
  { title: '状态', dataIndex: 'registration_status', width: 150, fixed: 'right' as const, align: 'center' as const },
  { title: '操作', dataIndex: 'action', width: 150, fixed: 'right' as const, align: 'center' as const },
])
const loading = shallowRef(false)
const pagination = computed<PaginationProps | false>(() => {
  // 当数据条数少于等于10条时，不显示分页
  if (paginationData.total <= 10) {
    return false
  }
  return {
    pageSize: paginationData.pageSize,
    pageSizeOptions: ['10', '20', '30', '40'],
    current: paginationData.current,
    total: paginationData.total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: total => `共 ${total} 条`,
    onChange(current, pageSize) {
      paginationData.pageSize = pageSize
      paginationData.current = current
      init()
    },
  }
})

const paginationData = reactive({
  pageSize: 10,
  current: 1,
  total: 0,
})
const dataSource = shallowRef<TableRow[]>([])

// 主题色系
const PRIMARY_COLOR = '#428bca'
const PRIMARY_COLOR_LIGHT = '#5fa2d6'
const PRIMARY_BUTTON_STYLE = {
  backgroundColor: PRIMARY_COLOR,
  border: 'none',
  borderRadius: '0px',
  fontSize: '16px',
  height: '36px',
  padding: '0 20px',
}

// 多选相关
const selectedRowKeys = ref<number[]>([])
const selectedRows = ref<TableRow[]>([])

// 主题色系
let themeColor = 'blue'

// 搜索表单
const searchForm = reactive({
  keyword: '', // 姓名搜索
  examSubject: 'all', // 考试科目
  dateRange: undefined as [string, string] | undefined,
  registrationStatus: '2,3', // 默认选择待审核（状态2和3）
})

// 科目列表
const subjectList = ref<ExamSubject[]>([])

// 状态选项
const statusOptions = [
  { value: '2,3', label: '待审核' }, // 状态2和3（缴费待审核）
  { value: '4,5,6', label: '已审核通过' }, // 状态4、5、6（已缴费成功）
  { value: '7,8', label: '已审核不通过' }, // 状态7和8（缴费审核拒绝）
  { value: 'all', label: '全部' }, // 包括所有状态（0待完善、1待缴费、2和3待审核、4/5/6已通过、7/8已拒绝）
]

// 通过审核按钮样式选择

// 导出 LIBF 报名记录
async function handleExportLibfRegistrations() {
  try {
    const params: any = {}
    
    // 添加时间范围
    if (searchForm.dateRange && Array.isArray(searchForm.dateRange) && searchForm.dateRange.length === 2) {
      const startDate = searchForm.dateRange[0] as any
      const endDate = searchForm.dateRange[1] as any
      params.startDate = typeof startDate === 'string' ? startDate : (startDate?.format ? startDate.format('YYYY-MM-DD') : String(startDate))
      params.endDate = typeof endDate === 'string' ? endDate : (endDate?.format ? endDate.format('YYYY-MM-DD') : String(endDate))
    }
    
    // 添加姓名模糊搜索
    if (searchForm.keyword) {
      params.name = searchForm.keyword
    }
    
    // 添加报名状态筛选
    if (searchForm.registrationStatus && searchForm.registrationStatus !== 'all') {
      params.registration_status = Number(searchForm.registrationStatus)
    }
    
    // 添加考试科目筛选
    if (searchForm.examSubject && searchForm.examSubject !== 'all') {
      params.subject_id = searchForm.examSubject
    }
    
    const response = await exportLibfRegistrationsApi(params)
    console.log(response,"11122233")
    if (response.code === 0 ) {
      const filePath = response.data
      // 构建下载地址
      const downloadUrl = `https://freesgpt.cn${filePath}`
      
      // 创建临时链接下载文件
      const link = document.createElement('a')
      link.href = downloadUrl
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      Modal.success({
        title: h('span', { style: 'font-size: 16px;' }, '提示'),
        content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333' }, 'LIBF报名记录导出成功'),
        okText: '确定',
        okButtonProps: { 
          style: { 
            ...PRIMARY_BUTTON_STYLE,
          },
        } as any,
        centered: true,
      })
    } else {
      const errorMsg = response.msg || response.data?.message || '导出失败，请重试'
      Modal.error({
        title: h('span', { style: 'font-size: 16px;' }, '错误'),
        content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, errorMsg),
        okText: '确定',
        okButtonProps: { 
          style: { 
            ...PRIMARY_BUTTON_STYLE,
          },
        } as any,
        centered: true,
      })
    }
  }
  catch (error) {
    console.error('导出LIBF报名记录失败:', error)
    Modal.error({
      title: h('span', { style: 'font-size: 16px;' }, '错误'),
      content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '导出LIBF报名记录失败，请重试'),
      okText: '确定',
      okButtonProps: { 
        style: { 
          ...PRIMARY_BUTTON_STYLE,
        },
      } as any,
      centered: true,
    })
  }
}

// 处理导出菜单点击
function handleExportMenuClick(info: { key: string | number }) {
  const key = String(info.key)
  if (key === 'libf') {
    handleExportLibfRegistrations()
  } else if (key === 'excel') {
    handleDownloadExcel()
  }
}

// 下载Excel（整个表格）
async function handleDownloadExcel() {
  try {
    // 获取所有数据（不分页）
    const response = await getRegistrationListApi({
      current: 1,
      pageSize: 10000, // 获取所有数据
    })
    
    if (response.code === 0 && response.data && Array.isArray(response.data)) {
      // 准备Excel数据
      const excelData = response.data.map((item: RegistrationItem) => ({
        '姓名': item.username || '',
        '性别': item.gender === 1 ? '男' : item.gender === 2 ? '女' : '未知',
        '报考科目': getSubjectDisplayName(item) || '',
        '报考费用': `¥${item.exam_fee || '0.00'}`,
        '姓（英文）': item.family_name || '',
        '名（英文）': item.given_name || '',
        '国家': item.country_en || '',
        '公司名称': item.company_name || '',
        '公司名称（英文）': item.company_name_en || '',
        '考生编号': item.examinee_number || '',
        '称谓（英文）': item.title_en || '',
        '出生日期（英文）': item.birth_date_en || '',
        '性别（英文）': item.gender_en || '',
        '状态': getRegistrationStatusText(item.registration_status),
        '报名时间': item.registration_time || '',
        '邮箱': item.email || '',
        '电话': item.phone || '',
      }))
      
      // 使用动态导入 xlsx 库
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const XLSX = await import('xlsx')
      
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      
      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(excelData)
      
      // 设置列宽
      const colWidths = [
        { wch: 10 }, // 姓名
        { wch: 8 },  // 性别
        { wch: 25 }, // 报考科目
        { wch: 12 }, // 报考费用
        { wch: 15 }, // 姓（英文）
        { wch: 15 }, // 名（英文）
        { wch: 12 }, // 国家
        { wch: 25 }, // 公司名称
        { wch: 40 }, // 公司名称（英文）
        { wch: 15 }, // 考生编号
        { wch: 15 }, // 称谓（英文）
        { wch: 18 }, // 出生日期（英文）
        { wch: 15 }, // 性别（英文）
        { wch: 15 }, // 状态
        { wch: 20 }, // 报名时间
        { wch: 25 }, // 邮箱
        { wch: 15 }, // 电话
      ]
      ws['!cols'] = colWidths
      
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, '报名列表')
      
      // 生成文件名
      const fileName = `报名列表_${new Date().toISOString().split('T')[0]}.xlsx`
      
      // 导出文件
      XLSX.writeFile(wb, fileName)
    }
    else {
      Modal.warning({
        title: h('span', { style: 'font-size: 16px;' }, '提示'),
        content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '暂无数据可导出'),
        okText: '确定',
        okButtonProps: { 
          style: { 
            backgroundColor: PRIMARY_COLOR, 
            border: 'none', 
            borderRadius: '0px',
            fontSize: '16px',
            height: '36px',
            padding: '0 20px',
          },
        } as any,
        centered: true,
      })
    }
  }
  catch (error) {
    console.error('导出Excel失败:', error)
    Modal.error({
      title: h('span', { style: 'font-size: 16px;' }, '错误'),
      content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '导出Excel失败，请确保已安装xlsx库'),
      okText: '确定',
      okButtonProps: { 
        style: { 
          backgroundColor: PRIMARY_COLOR, 
          border: 'none', 
          borderRadius: '0px',
          fontSize: '16px',
          height: '36px',
          padding: '0 20px',
        },
      } as any,
      centered: true,
    })
  }
}

const tableSize = ref<string[]>(['large'])

const open = ref(false)
const detailDrawerVisible = ref(false)
const currentDetailRow = ref<TableRow | null>(null)
const drawerTitle = computed(() => {
  if (currentDetailRow.value?.username) {
    return `${currentDetailRow.value.username} 的报名详情`
  }
  return '报名详情'
})
const isDrawerApproveEnabled = computed(() => currentDetailRow.value?.registration_status === 2 || currentDetailRow.value?.registration_status === 3)

const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const params: any = {
      current: paginationData.current,
      pageSize: paginationData.pageSize,
    }
    
    // 添加姓名搜索
    if (searchForm.keyword) {
      params.name = searchForm.keyword
      params.keyword = searchForm.keyword // 同时使用两个参数名，兼容不同接口
    }
    
    // 添加考试科目筛选 - 尝试多种参数名称
    if (searchForm.examSubject && searchForm.examSubject !== 'all') {
      const subjectId = Number(searchForm.examSubject)
      params.subject_id = subjectId
      params.exam_subject_id = subjectId
      params.subjectId = subjectId
    }
    
    // 添加报名状态筛选（支持多个状态值）
    if (searchForm.registrationStatus && searchForm.registrationStatus !== 'all') {
      // 如果包含逗号，说明是多个状态值，需要在前端筛选
      // 这里先不传参数，让前端筛选处理
    }
    
    // 添加时间范围
    if (searchForm.dateRange && Array.isArray(searchForm.dateRange) && searchForm.dateRange.length === 2) {
      // 处理 dayjs 对象或字符串
      const startDate = searchForm.dateRange[0] as any
      const endDate = searchForm.dateRange[1] as any
      params.startDate = typeof startDate === 'string' ? startDate : (startDate?.format ? startDate.format('YYYY-MM-DD') : String(startDate))
      params.endDate = typeof endDate === 'string' ? endDate : (endDate?.format ? endDate.format('YYYY-MM-DD') : String(endDate))
    }
    
    const response = await getRegistrationListApi(params)
    
    if (response.code === 0 && response.data && Array.isArray(response.data)) {
      let filteredData: RegistrationItem[] = response.data
      
      // 如果后端不支持筛选，在前端进行筛选
      // 按姓名筛选
      if (searchForm.keyword) {
        const keyword = searchForm.keyword.toLowerCase().trim()
        filteredData = filteredData.filter((item: RegistrationItem) => {
          const username = (item.username || '').toLowerCase()
          return username.includes(keyword)
        })
      }
      
      // 按考试科目筛选
      if (searchForm.examSubject && searchForm.examSubject !== 'all') {
        const subjectId = Number(searchForm.examSubject)
        const selectedSubject = subjectList.value.find(s => Number(s.id) === subjectId)
        filteredData = filteredData.filter((item: RegistrationItem) => {
          // 匹配科目ID（支持数字和字符串比较）
          if (item.exam_subject?.id && (Number(item.exam_subject.id) === subjectId || item.exam_subject.id === subjectId)) {
            return true
          }
          // 匹配科目代码
          if (selectedSubject && item.subject_code === selectedSubject.subject_code) {
            return true
          }
          // 匹配科目名称（精确匹配）
          if (selectedSubject && getSubjectDisplayName(item) === getSubjectDisplayName({ exam_subject: selectedSubject } as RegistrationItem)) {
            return true
          }
          return false
        })
      }
      
      // 按状态筛选（支持多个状态值，用逗号分隔）
      if (searchForm.registrationStatus && searchForm.registrationStatus !== 'all') {
        const statusValues = searchForm.registrationStatus.split(',').map(s => Number(s.trim()))
        filteredData = filteredData.filter((item: RegistrationItem) => {
          return statusValues.includes(item.registration_status)
        })
      }
      
      // 按时间范围筛选
      if (searchForm.dateRange && Array.isArray(searchForm.dateRange) && searchForm.dateRange.length === 2) {
        const startDate = searchForm.dateRange[0] as any
        const endDate = searchForm.dateRange[1] as any
        const start = typeof startDate === 'string' ? startDate : (startDate?.format ? startDate.format('YYYY-MM-DD') : String(startDate))
        const end = typeof endDate === 'string' ? endDate : (endDate?.format ? endDate.format('YYYY-MM-DD') : String(endDate))
        
        filteredData = filteredData.filter((item: RegistrationItem) => {
          if (!item.registration_time) return false
          const regDate = item.registration_time.split(' ')[0] // 只取日期部分
          return regDate >= start && regDate <= end
        })
      }
      
      // 转换数据格式，添加 key 字段
      const formattedData: TableRow[] = filteredData.map((item: RegistrationItem, index: number) => ({
        ...item,
        key: item.id || index,
      }))
      dataSource.value = formattedData
      // 如果后端返回了总数，使用后端的总数，否则使用当前数据长度
      paginationData.total = filteredData.length || formattedData.length
    }
    else {
      dataSource.value = []
      paginationData.total = 0
    }
  }
  catch (error) {
    console.error('获取报名列表失败:', error)
    dataSource.value = []
    paginationData.total = 0
  }
  finally {
    loading.value = false
  }
}

async function onSearch() {
  paginationData.current = 1
  await init()
}

// 重置搜索
function onReset() {
  searchForm.keyword = ''
  searchForm.examSubject = 'all'
  searchForm.dateRange = undefined
  searchForm.registrationStatus = '2,3' // 重置为默认的待审核状态
  paginationData.current = 1
  init()
}

// 科目选择情况
function handleExamSubjectChange(value: any) {
  // 确保值是字符串
  searchForm.examSubject = value === 'all' || value === null || value === undefined ? 'all' : String(value)
  paginationData.current = 1
  init()
}

// 报名状态选择变化
function handleRegistrationStatusChange(value: any) {
  // 确保值是字符串
  searchForm.registrationStatus = value || 'all'
  paginationData.current = 1
  init()
}

// 获取科目列表
async function loadSubjects() {
  try {
    const response = await getSubjectsApi()
    if (response.code === 0 && response.data && Array.isArray(response.data)) {
      subjectList.value = response.data
    }
  }
  catch (error) {
    console.error('获取科目列表失败:', error)
  }
}

// 预留：未使用，保留占位避免误删
// async function onReset() {
//   await init()
// }

// 通过审核
async function handleApprove(row: TableRow) {
  const subjectName = getSubjectDisplayName(row)
  const registrationType = getRegistrationType(row)
  const confirmContent = h('div', null, [
    '确定要通过 ',
    h('span', { style: { fontWeight: 'bold' } }, row.username),
    ' - ',
    h('span', { style: { fontWeight: 'bold' } }, `${subjectName}${registrationType}`),
    ' 的审核吗？'
  ]);
  Modal.confirm({
    title: h('span', { style: 'font-size: 16px;' }, '操作提示'),
    icon: h(ExclamationCircleFilled, { style: { color: PRIMARY_COLOR } }),
    content: confirmContent,
    okText: '确定',
    cancelText: '取消',
    okButtonProps: { 
      style: { 
        backgroundColor: PRIMARY_COLOR, 
        border: 'none', 
        borderRadius: '0px',
        fontSize: '16px',
        height: '36px',
        padding: '0 20px',
      },
    } as any,
    cancelButtonProps: { 
      style: { 
        fontSize: '16px',
        height: '36px',
        padding: '0 20px',
        borderRadius: '0px',
      },
    } as any,
    centered: true,
    onOk: async () => {
      try {
        let newStatus: number
        // 状态2通过 → 4
        if(row.registration_status === 2){
          newStatus = 4
        }
        // 状态3通过 → 5
        else if(row.registration_status === 3){
          newStatus = 5
        }
        else {
          Modal.error({
            title: h('span', { style: 'font-size: 16px;' }, '错误'),
            content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '当前状态不支持此操作'),
            okText: '确定',
            okButtonProps: { 
              style: { 
                backgroundColor: PRIMARY_COLOR, 
                border: 'none', 
                borderRadius: '0px',
                fontSize: '16px',
                height: '36px',
                padding: '0 20px',
              },
            } as any,
            centered: true,
          })
          return
        }

        const response = await updateRegistrationStatusApi({
          id: row.id,
          registration_status: newStatus,
        })
        if (response.code === 0) {
          Modal.info({
            title: h('span', { style: 'font-size: 16px;' }, '提示'),
            content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '审核通过'),
            icon: h(ExclamationCircleFilled, { style: { color: PRIMARY_COLOR } }),
            centered: true,
          })
          setTimeout(() => {
            Modal.destroyAll()
          }, 1000)
          await refreshListKeepPosition()
          if (detailDrawerVisible.value) {
            detailDrawerVisible.value = false
            currentDetailRow.value = null
          }
        }
      }
      catch (error) {
        console.error('审核失败:', error)
        Modal.error({
          title: h('span', { style: 'font-size: 16px;' }, '错误'),
          content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '审核失败，请重试'),
          okText: '确定',
          okButtonProps: { 
            style: { 
              backgroundColor: PRIMARY_COLOR, 
              border: 'none', 
              borderRadius: '0px',
              fontSize: '16px',
              height: '36px',
              padding: '0 20px',
            },
          } as any,
          centered: true,
        })
      }
    },
  })
}

// 不通过审核
async function handleReject(row: TableRow) {
  const subjectName = getSubjectDisplayName(row)
  const registrationType = getRegistrationType(row)
  const confirmContent = h('div', null, [
    '确定要不通过 ',
    h('span', { style: { fontWeight: 'bold' } }, row.username),
    ' - ',
    h('span', { style: { fontWeight: 'bold' } }, `${subjectName}${registrationType}`),
    ' 的审核吗？'
  ]);
  Modal.confirm({
    title: h('span', { style: 'font-size: 16px;' }, '操作提示'),
    icon: h(ExclamationCircleFilled, { style: { color: '#ff4d4f' } }),
    content: confirmContent,
    okText: '确定',
    cancelText: '取消',
    okButtonProps: { 
      style: { 
        backgroundColor: '#ff4d4f', 
        border: 'none', 
        borderRadius: '0px',
        fontSize: '16px',
        height: '36px',
        padding: '0 20px',
      },
    } as any,
    cancelButtonProps: { 
      style: { 
        fontSize: '16px',
        height: '36px',
        padding: '0 20px',
        borderRadius: '0px',
      },
    } as any,
    centered: true,
    onOk: async () => {
      try {
        let newStatus: number
        // 状态2不通过 → 7（缴费审核拒绝，未申请开发票）
        if(row.registration_status === 2){
          newStatus = 7
        }
        // 状态3不通过 → 8（缴费审核拒绝，已申请开发票，发票未开票失败）
        else if(row.registration_status === 3){
          newStatus = 8
        }
        else {
          Modal.error({
            title: h('span', { style: 'font-size: 16px;' }, '错误'),
            content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '当前状态不支持此操作'),
            okText: '确定',
            okButtonProps: { 
              style: { 
                backgroundColor: PRIMARY_COLOR, 
                border: 'none', 
                borderRadius: '0px',
                fontSize: '16px',
                height: '36px',
                padding: '0 20px',
              },
            } as any,
            centered: true,
          })
          return
        }

        const response = await updateRegistrationStatusApi({
          id: row.id,
          registration_status: newStatus,
        })
        if (response.code === 0) {
          Modal.info({
            title: h('span', { style: 'font-size: 16px;' }, '提示'),
            content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '已标记为不通过'),
            icon: h(ExclamationCircleFilled, { style: { color: '#ff4d4f' } }),
            centered: true,
          })
          setTimeout(() => {
            Modal.destroyAll()
          }, 1000)
          await refreshListKeepPosition()
          if (detailDrawerVisible.value) {
            detailDrawerVisible.value = false
            currentDetailRow.value = null
          }
        }
      }
      catch (error) {
        console.error('审核失败:', error)
        Modal.error({
          title: h('span', { style: 'font-size: 16px;' }, '错误'),
          content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '操作失败，请重试'),
          okText: '确定',
          okButtonProps: { 
            style: { 
              backgroundColor: PRIMARY_COLOR, 
              border: 'none', 
              borderRadius: '0px',
              fontSize: '16px',
              height: '36px',
              padding: '0 20px',
            },
          } as any,
          centered: true,
        })
      }
    },
  })
}

// 查看详情
function handleView(row: TableRow) {
  currentDetailRow.value = row
  detailDrawerVisible.value = true
}

function handleDrawerClose() {
  detailDrawerVisible.value = false
  currentDetailRow.value = null
}

function handleDrawerApprove() {
  if (!currentDetailRow.value) {
    return
  }
  handleApprove(currentDetailRow.value)
}

function handleDrawerReject() {
  if (!currentDetailRow.value) {
    return
  }
  handleReject(currentDetailRow.value)
}

// 刷新列表但保持当前位置
async function refreshListKeepPosition() {
  const currentPage = paginationData.current
  const currentScrollTop = document.querySelector('.table-wrapper')?.scrollTop || 0
  
  await init()
  
  // 恢复页码
  paginationData.current = currentPage
  
  // 恢复滚动位置
  nextTick(() => {
    const wrapper = document.querySelector('.table-wrapper')
    if (wrapper) {
      wrapper.scrollTop = currentScrollTop
    }
  })
}

// 批量审核
async function handleBatchApprove() {
  if (selectedRowKeys.value.length === 0) {
    Modal.warning({
      title: h('span', { style: 'font-size: 16px;' }, '提示'),
      content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '请先选择要审核的记录'),
      okText: '确定',
      okButtonProps: { 
        style: { 
          backgroundColor: PRIMARY_COLOR, 
          border: 'none', 
          borderRadius: '0px',
          fontSize: '16px',
          height: '36px',
          padding: '0 20px',
        },
      } as any,
      centered: true,
    })
    return
  }
  
  Modal.confirm({
    title: h('span', { style: 'font-size: 16px;' }, '批量审核确认'),
    content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, `确定要批量审核 ${selectedRowKeys.value.length} 条记录吗？`),
    icon: h(ExclamationCircleFilled, { style: { color: PRIMARY_COLOR } }),
    okText: '确定',
    cancelText: '取消',
    okButtonProps: { 
      style: { 
        backgroundColor: PRIMARY_COLOR, 
        border: 'none', 
        borderRadius: '0px',
        fontSize: '16px',
        height: '36px',
        padding: '0 20px',
      },
    } as any,
    cancelButtonProps: { 
      style: { 
        fontSize: '16px',
        height: '36px',
        padding: '0 20px',
      },
    } as any,
    centered: true,
    onOk: async () => {
      try {
        const response = await batchApproveRegistrationApi({
          ids: selectedRowKeys.value,
          registration_status: 3,
        })
        
        if (response.code === 0) {
          Modal.info({
            title: h('span', { style: 'font-size: 16px;' }, '提示'),
            content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, `成功审核 ${selectedRowKeys.value.length} 条记录`),
            icon: h(ExclamationCircleFilled, { style: { color: PRIMARY_COLOR } }),
            okText: '确定',
            okButtonProps: { 
              style: { 
                backgroundColor: PRIMARY_COLOR, 
                border: 'none', 
                borderRadius: '0px',
                fontSize: '16px',
                height: '36px',
                padding: '0 20px',
              },
            } as any,
            centered: true,
          })
          selectedRowKeys.value = []
          selectedRows.value = []
          // 刷新列表但保持当前位置
          await refreshListKeepPosition()
        }
      }
      catch (error) {
        console.error('批量审核失败:', error)
        Modal.error({
          title: h('span', { style: 'font-size: 16px;' }, '错误'),
          content: h('div', { style: 'font-size: 16px; line-height: 24px; color: #333;' }, '批量审核失败，请重试'),
          okText: '确定',
          okButtonProps: { 
            style: { 
              backgroundColor: PRIMARY_COLOR, 
              border: 'none', 
              borderRadius: '0px',
              fontSize: '16px',
              height: '36px',
              padding: '0 20px',
            },
          } as any,
          centered: true,
        })
      }
    },
  })
}

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: (string | number)[], rows: TableRow[]) => {
    selectedRowKeys.value = keys as number[]
    selectedRows.value = rows
  },
  onSelectAll: (selected: boolean, _selectedRows: TableRow[], changeRows: TableRow[]) => {
    if (selected) {
      selectedRowKeys.value = changeRows.map((row: TableRow) => row.key)
      selectedRows.value = changeRows
    } else {
      const changeKeys = changeRows.map((row: TableRow) => row.key)
      selectedRowKeys.value = selectedRowKeys.value.filter(key => !changeKeys.includes(key))
      selectedRows.value = selectedRows.value.filter(row => !changeKeys.includes(row.key))
    }
  },
}))

/**
 * 新增事件
 *
 */
function handleOk() {
  open.value = false
  Modal.destroyAll()
  onSearch()
}

/**


/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

/**
 * 全选/反选事件
 *
 */


watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)

/**
 * 重置事件
 *
 */


/**
 * checkbox点击事件
 *
 */
const handleCheckChange = (value: string[]) => {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}

defineExpose({
  handleCheckChange,
})

onMounted(() => {
  loadSubjects()
  init()
})

// 预留展开开关，当前未使用
// const expand = ref(false)
</script>

<template>
  <page-container>
      <!-- 搜索表单 -->
   
      
      <div class="table-toolbar">
        <a-space size="large">
          <a-form 
      :model="searchForm" layout="inline">
      <a-form-item
      style="
          padding-top: 8px;;
          "
      >
        <template
            #label>
              <span
              style="
              color:black;
              font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Microsoft YaHei', 'Hiragino Sans GB', 'WenQuanYi Micro Hei', Arial, 'SimSun', 'sans-serif';
              font-size:15px;
              font-weight: 500;
              "
              >
               姓名
              </span>
            </template>
            <a-input
              v-model:value="searchForm.keyword"
              placeholder="请输入姓名"
              style="width: 200px;
                position:relative;
                top:-5px;
                height: 40px;
                border-radius: 10px;"
              allow-clear
              @press-enter="onSearch"
            />
      </a-form-item>
      <a-form-item
      style="
          padding-top: 8px;;
          "
      >
        <template
            #label>
              <span
              style="
              color:black;
              font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Microsoft YaHei', 'Hiragino Sans GB', 'WenQuanYi Micro Hei', Arial, 'SimSun', 'sans-serif';
              font-size:15px;
              font-weight: 500;
              "
              >
               考试科目
              </span>
            </template>
            <a-select
            style="
                position:relative;
                top:-5px;
                border-radius: 10px;;
            "
              v-model:value="searchForm.examSubject"
              @change="handleExamSubjectChange"
              class="audit-status-select"
            >
            <a-select-option :value="'all'">全部</a-select-option>
              <a-select-option 
                v-for="subject in subjectList" 
                :key="subject.id" 
                :value="String(subject.id)">
                {{ subject.subject_name }}
              </a-select-option>
            </a-select>
      </a-form-item>
      <a-form-item 
      style="
          padding-top: 8px;;
          "
      >
            <template
            #label>
              <span
              style="
              color:black;
              font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Microsoft YaHei', 'Hiragino Sans GB', 'WenQuanYi Micro Hei', Arial, 'SimSun', 'sans-serif';
              font-size:15px;
              font-weight: 500;
              "
              >
                状态
              </span>
            </template>
            <a-select
            style="
                position:relative;
                top:-5px;
                border-radius: 10px;;
            "
              v-model:value="searchForm.registrationStatus"
              @change="handleRegistrationStatusChange"
              class="audit-status-select"
            >
              <a-select-option 
                v-for="option in statusOptions" 
                :key="option.value" 
                :value="option.value">
                {{ option.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item 
          style="
          padding-top: 8px;;
          "
          >
            <template
            #label>
              <span
              style="
              color:black;
           
              font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Microsoft YaHei', 'Hiragino Sans GB', 'WenQuanYi Micro Hei', Arial, 'SimSun', 'sans-serif';
              font-size:15px;
              font-weight: 500;
              "
              >
                报名时间
              </span>
            </template>
            <a-range-picker
              v-model:value="searchForm.dateRange"
              style="width: 220px;
                 position: relative;
                 top:-5px;
              height: 40px;
              "
              format="YYYY-MM-DD"
            />
          </a-form-item>
          <a-form-item
          style="
          padding-top: 8px;;
          "
          >
            <a-space>
              <a-button
                style="
                  height: 36px;
                  border-radius: 0px;
                  position: relative;
                  top:-2px;
                "
                class="primary-btn"
                type="primary"
                @click="onSearch">
                查询
              </a-button>
              <a-button 
                style="
                  height: 36px;
                  border-radius: 0px;
                  position: relative;
                  top:-2px;
                "
                class="primary-btn ghost-btn"
                @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
   
        </a-space>
        <a-space size="middle">
          <a-button 
            class="batch-approve-btn"
            type="primary" 
            size="large"
            :disabled="selectedRowKeys.length === 0"
            @click="handleBatchApprove">
            批量审核 ({{ selectedRowKeys.length }})
          </a-button>
          <a-button 
            class="refresh-btn"
            size="large"
            @click="onSearch">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-dropdown>
            <template #overlay>
              <a-menu @click="handleExportMenuClick">
                <a-menu-item key="libf">
                  下载LIBF报名记录
                </a-menu-item>
                <a-menu-item
                style="
                display:block;
                "
                key="excel">
                  下载完整字段表格
                </a-menu-item>
              </a-menu>
            </template>
            <a-button 
              class="download-excel-btn"
              type="primary"
              size="large">
              <template #icon>
                <DownloadOutlined />
              </template>
              导出
            </a-button>
          </a-dropdown>
        </a-space>
        <a-space
        style="
        display:none;
        "
        size="middle">
          <span>主题色系：</span>
          <a-radio-group v-model:value="themeColor" size="small">
            <a-radio-button value="blue">蓝色</a-radio-button>
            <a-radio-button value="green">绿色</a-radio-button>
            <a-radio-button value="purple">紫色</a-radio-button>
            <a-radio-button value="cyan">青绿色</a-radio-button>
          </a-radio-group>
        </a-space>
      </div>
      <!-- <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="() => open = true">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
          <a-tooltip title="列设置">
            <a-dropdown v-model:open="dropdownVisible" trigger="click">
              <SettingOutlined />
              <template #overlay>
                <a-card>
                  <template #title>
                    <a-checkbox v-model:checked="state.checkAll" :indeterminate="state.indeterminate" @change="handleCheckAllChange">
                      列选择
                    </a-checkbox>
                  </template>
                  <template #extra>
                    <a-button type="link" @click="handleResetChange">
                      重置
                    </a-button>
                  </template>
                  <a-checkbox-group v-model:value="state.checkList" :options="options" style="display: flex; flex-direction: column;" @change="handleCheckChange" />
                </a-card>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template> -->
      <div class="table-wrapper" :class="`theme-${themeColor}`">
        <a-table 
          :loading="loading" 
          :columns="filterColumns"
          :data-source="dataSource"
          :pagination="pagination" 
          :size="tableSize[0] as TableProps['size']"
          :scroll="{ x: 'max-content', y: 'calc(100vh - 350px)' }"
          :row-selection="rowSelection"
          class="exam-table">
          <template #bodyCell="scope">
            <template v-if="scope?.column?.dataIndex === 'gender'">
              <span>{{ scope.record.gender === 1 ? '男' : scope.record.gender === 2 ? '女' : '未知' }}</span>
            </template>
            <template v-else-if="scope?.column?.dataIndex === 'exam_subject'">
              <span 
                class="subject-name-cell"
                :class="getRegistrationType(scope.record as RegistrationItem) === '补考' ? 'subject-retake' : 'subject-first'"
              >
                {{ getSubjectDisplayName(scope.record as RegistrationItem) || '-' }}
              </span>
            </template>
            <template v-else-if="scope?.column?.dataIndex === 'fee'">
              <span>¥{{ getCorrectFee(scope.record as RegistrationItem) }}</span>
            </template>
            <template v-else-if="scope?.column?.dataIndex === 'registration_status'">
              <div class="status-cell">
                <CheckCircleOutlined 
                  v-if="scope.record.registration_status === 4 || scope.record.registration_status === 5 || scope.record.registration_status === 6"
                  :style="{ color: PRIMARY_COLOR_LIGHT, marginRight: '6px', fontSize: '16px' }" 
                />
                <ExclamationCircleOutlined 
                  v-else-if="scope.record.registration_status === 7 || scope.record.registration_status === 8"
                  :style="{ color: '#ff4d4f', marginRight: '6px', fontSize: '16px' }" 
                />
                <ExclamationCircleOutlined 
                  v-else
                  :style="{ color: PRIMARY_COLOR_LIGHT, marginRight: '6px', fontSize: '16px' }" 
                />
                <span>{{ getRegistrationStatusText(scope.record.registration_status) }}</span>
              </div>
            </template>
            <template v-else-if="scope?.column?.dataIndex === 'payment_proof'">
              <div v-if="scope.record.payment_proof" class="payment-proof-images">
                <Image
                  v-for="(img, index) in getPaymentProofImages(scope.record.payment_proof)"
                  :key="index"
                  :src="img"
                  :width="35"
                  :height="35"
                  :preview="true"
                  class="payment-proof-img"
                />
              </div>
              <span v-else>-</span>
            </template>
            <template v-else-if="scope?.column?.dataIndex === 'action'">
              <div class="action-cell">
                <!-- 待审核（状态2或3）：显示通过审核、不通过审核和查看按钮 -->
                <template v-if="scope.record.registration_status === 2
                || scope.record.registration_status === 3">
                  <a-button
                    class="approve-btn approve-btn-style1"
                    type="primary" 
                    @click="handleApprove(scope?.record as TableRow)">
                    通过审核
                  </a-button>
                  <a-button
                    class="reject-btn"
                    danger
                    @click="handleReject(scope?.record as TableRow)">
                    不通过审核
                  </a-button>
                  <a-button
                    class="view-btn"
                    @click="handleView(scope?.record as TableRow)">
                    查看
                  </a-button>
                </template>
                <!-- 其他状态：只显示查看按钮 -->
                <template v-else>
                  <a-button
                    class="view-btn"
                    @click="handleView(scope?.record as TableRow)">
                    查看
                  </a-button>
                </template>
              </div>
            </template>
          </template>
        </a-table>
      </div>
      <a-drawer
        v-model:open="detailDrawerVisible"
        :title="drawerTitle"
        placement="right"
        width="660"
        destroy-on-close
        class="detail-drawer"
        @close="handleDrawerClose"
      >
        <template v-if="currentDetailRow">
          <a-descriptions
            title="基本信息"
            :column="2"
            bordered
            size="small"
            class="detail-descriptions"
          >
            <a-descriptions-item label="姓名">
              {{ currentDetailRow.username || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="审核状态">
              {{ getRegistrationStatusText(currentDetailRow.registration_status) }}
            </a-descriptions-item>
            <a-descriptions-item label="姓（英文）">
              {{ currentDetailRow.family_name || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="名（英文）">
              {{ currentDetailRow.given_name || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="称谓（英文）">
              {{ currentDetailRow.title_en || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="性别">
              {{ currentDetailRow.gender === 1 ? '男' : currentDetailRow.gender === 0 ? '女' : '未知' }}
            </a-descriptions-item>
            <a-descriptions-item label="性别（英文）">
              {{ currentDetailRow.gender_en || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="出生日期">
              {{ currentDetailRow.birth_date || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="出生日期（英文）">
              {{ currentDetailRow.birth_date_en || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="LIBF NUMBER">
              {{ currentDetailRow.examinee_number || '-' }}
            </a-descriptions-item>
          </a-descriptions>

          <a-descriptions
          style="
          margin-top: 20px;
            "
            title="报考信息"
            :column="2"
            bordered
            size="small"
            class="detail-descriptions"
          >
            <a-descriptions-item 
            :span="2"
            label="报名时间">
              {{ currentDetailRow.registration_time || '-' }}
            </a-descriptions-item>
            <a-descriptions-item
            :span="2"
            label="报考类型">
              <span 
                class="registration-type-badge"
                :class="getRegistrationType(currentDetailRow) === '补考' ? 'type-retake' : 'type-first'"
              >
                {{ getRegistrationType(currentDetailRow) }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item 
            :span="2"
            label="考试科目">
              {{ getSubjectDisplayName(currentDetailRow) || '-' }}
            </a-descriptions-item>
            <a-descriptions-item 
            :span="2"
            label="是否报名培训">
              {{ currentDetailRow.pre_exam_training === 1 ? '是' :
               currentDetailRow.pre_exam_training === 2 ? '否' :
               '未填写' }}
            </a-descriptions-item>
            <a-descriptions-item 
            :span="2"
            label="报考单元">
              {{ getExamUnitText(currentDetailRow.makeup_unit) || (currentDetailRow.exam_subject?.exam_unit || '-') }}
            </a-descriptions-item>
          </a-descriptions>

          <a-descriptions
          style="
          margin-top: 20px;
            "
            title="联系与公司信息"
            :column="2"
            bordered
            size="small"
            class="detail-descriptions"
          >
            <a-descriptions-item 
             :span="2"
            label="手机号码">
              {{ currentDetailRow.phone || '-' }}
            </a-descriptions-item>
            <a-descriptions-item 
             :span="2"
            label="邮箱">
              {{ currentDetailRow.email || '-' }}
            </a-descriptions-item>
            <a-descriptions-item 
             :span="2"
            label="国家（英文）">
              {{ currentDetailRow.country_en || '-' }}
            </a-descriptions-item>
            <a-descriptions-item 
             :span="2"
            label="公司名称">
              {{ currentDetailRow.company_name || '-' }}
            </a-descriptions-item>
            <a-descriptions-item
             :span="2"
            label="公司名称（英文）">
              {{ currentDetailRow.company_name_en || '-' }}
            </a-descriptions-item>
          </a-descriptions>

          <a-descriptions
          style="
          margin-top: 20px;
            "
            title="地址信息"
            :column="2"
            bordered
            size="small"
            class="detail-descriptions"
          >
            <a-descriptions-item
            :span="2"
            label="地址">
              {{ currentDetailRow.address || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="英文地址">
              {{ currentDetailRow.address_en || '-' }}
            </a-descriptions-item>
          </a-descriptions>

          <a-descriptions
          style="
          margin-top: 20px;
            "
            :column="2"
            bordered
            size="small"
            class="detail-descriptions"
          >
          <template #title>
            <span  
            >
              支付信息
            </span>
          </template>
            <a-descriptions-item label="报考费用">
              ¥{{ getCorrectFee(currentDetailRow) }}
            </a-descriptions-item>
            <a-descriptions-item label="支付状态">
              {{ getPaymentStatusText(currentDetailRow.registration_status) }}
            </a-descriptions-item>

            <a-descriptions-item label="付款凭证">
              <div v-if="currentDetailRow.payment_proof" class="payment-proof-images">
                <Image
                  v-for="(img, index) in getPaymentProofImages(currentDetailRow.payment_proof)"
                  :key="index"
                  :src="img"
                  :width="60"
                  :height="60"
                  :preview="true"
                  class="payment-proof-img"
                />
              </div>
              <span v-else>-</span>
            </a-descriptions-item>
          </a-descriptions>

        </template>
        <div v-else class="drawer-empty">
          <a-empty description="暂无数据" />
        </div>
        <template #footer>
          <div class="drawer-footer">
            <a-space>
              <a-button
                v-if="isDrawerApproveEnabled"
                class="approve-btn approve-btn-style1 drawer-approve-btn"
                type="primary"
                @click="handleDrawerApprove"
              >
                通过审核
              </a-button>
              <a-button
                v-if="isDrawerApproveEnabled"
                class="reject-btn drawer-reject-btn"
                danger
                @click="handleDrawerReject"
              >
                不通过审核
              </a-button>
              <a-button 
                style="display: none;"
                class="drawer-cancel-btn" @click="handleDrawerClose">
                取消
              </a-button>
            </a-space> 
          </div>
        </template>
      </a-drawer>
    <a-modal v-model:open="open" title="新建规则" width="400px" @ok="handleOk">
      <a-space direction="vertical" size="large" class="w-full">
        <a-input placeholder="请输入" />
        <a-textarea placeholder="请输入" />
      </a-space>
    </a-modal>
  </page-container>
</template>

<style lang="less" scoped>
@primary-color: #428bca;
@primary-color-light: #5fa2d6;
@primary-color-muted: #9cb6de;
@primary-color-soft: #dfe8f6;
@primary-color-dark: #2f5c93;
.search-card {
  margin-bottom: 16px;
  
  :deep(.ant-card-body) {
    padding: 16px;
  }
  
  :deep(.ant-form-item) {
    margin-bottom: 0;
  }
  
  :deep(.ant-btn) {
    border-radius: 0px;
  }
  
  :deep(.ant-input) {
    border-radius: 0px;
  }
  
  :deep(.ant-picker) {
    border-radius: 0px;
  }
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 1px 2px;
  border-radius: 0px;
  position: relative;
  top:-15px;
}

.audit-status-select {
  min-width: 280px;

  :deep(.ant-select-selector) {
    height: 40px !important;
    border-radius: 4px !important;
    padding: 0 12px;
    display: flex;
    align-items: center;
  }

  :deep(.ant-select-selection-search-input) {
    height: 40px !important;
  }

  :deep(.ant-select-selection-item),
  :deep(.ant-select-selection-placeholder) {
    line-height: 40px !important;
    color: #000000 !important;
  }

  :deep(.ant-select-arrow) {
    color: #000000 !important;
  }
}

.primary-btn {
  background: linear-gradient(135deg, @primary-color 0%, @primary-color-light 100%);
  border: none;
  color: #fff;
  font-weight: 500;
  box-shadow: 0 2px 6px fade(@primary-color, 35%);
  transition: all 0.2s;

  &:hover {
    background: linear-gradient(135deg, @primary-color-dark 0%, @primary-color-light 100%);
    color: #fff !important;
  }
}

.ghost-btn {
  background: transparent !important;
  border: 1px solid @primary-color !important;
  color: @primary-color !important;
  box-shadow: none;

  &:hover {
    color: #fff !important;
    background: @primary-color !important;
  }
}

.table-wrapper {
  overflow-x: auto;
  width: 100%;
  position: relative;
  top:-15px;
  
  // 自定义滚动条样式 - 青绿色系，更细一点
  &::-webkit-scrollbar {
    height: 1px;
    width: 1px;
  }
  
  &::-webkit-scrollbar-track {
    border-radius: 2px;
  }
  
  &::-webkit-scrollbar-thumb {
    border-radius: 0px;
    transition: background 0.3s;
    
    &:hover {
      background: @primary-color-light;
    }
  }
  
  // Firefox 滚动条样式
  scrollbar-width: 1px;
}

.detail-drawer {
  :deep(.ant-drawer-header) {
    border-bottom: 1px solid #e4e7ed;
  }

  :deep(.ant-drawer-body) {
    padding: 12px 24px 24px;
  }

  :deep(.ant-drawer-footer) {
    border-top: 1px solid #e4e7ed;
    padding: 12px 24px;
    text-align: right;
    background-color: #fafafa;
  }
}

.detail-descriptions {
  :deep(.ant-descriptions-item-label) {
    width: 150px;
    font-weight: 500;
  }

  :deep(.ant-descriptions-item-content) {
    color: #333;
  }
}

.drawer-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
}

.drawer-approve-btn {
  min-width: 120px;
}

.drawer-cancel-btn {
  height: 36px;
  border-radius: 2px;
  min-width: 96px;
}

.exam-table {
  font-size: 18px;

  :deep(.ant-table-thead > tr > th) {
    font-size: 16px !important;
    font-weight: 500 !important;
    text-align: center !important;
    border-bottom: 1px solid #e4e7ed !important;
  }

  :deep(.ant-table-tbody > tr > td) {
    font-size: 16px !important;
    text-align: center !important;
  }
  
  // 表体单元格内容居中
  :deep(.ant-table-tbody > tr > td > span),
  :deep(.ant-table-tbody > tr > td > div) {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  :deep(.ant-pagination) {
    font-size: 16px !important;
    margin-top: 12px;

    .ant-pagination-total-text {
      color: @primary-color;
      font-weight: 500;
    }

    .ant-pagination-item {
      border-radius: 0;
      border-color: fade(@primary-color, 40%);

      a {
        color: @primary-color;
      }
    }

    .ant-pagination-item:hover {
      border-color: @primary-color;

      a {
        color: @primary-color-dark;
      }
    }

    .ant-pagination-item-active {
      background: @primary-color;
      border-color: @primary-color;

      a {
        color: #fff;
      }
    }

    .ant-pagination-prev .ant-pagination-item-link,
    .ant-pagination-next .ant-pagination-item-link {
      border-radius: 0;
      border-color: fade(@primary-color, 35%);
      color: @primary-color;

      &:hover {
        border-color: @primary-color;
        color: @primary-color-dark;
      }
    }
  }

  // 固定操作列样式
  :deep(.ant-table-cell-fix-right) {
    background-color: #fff;
    z-index: 1;
  }

  :deep(.ant-table-thead > tr > th.ant-table-cell-fix-right) {
    z-index: 1;
  }
  
  // 行选择框居中
  :deep(.ant-table-selection-column) {
    text-align: center;
  }
  
  // Loading图标颜色 - 青绿色调
  :deep(.ant-spin-dot-item) {
    background-color: @primary-color-light !important;
  }
  
  :deep(.ant-spin) {
    color: @primary-color-light !important;
  }
  
  :deep(.ant-table-spin-holder) {
    .ant-spin-dot-item {
      background-color: @primary-color-light !important;
    }
  }
}

.theme-blue,
.theme-green,
.theme-purple,
.theme-cyan {
  :deep(.ant-table-thead > tr > th) {
    background-color: @primary-color-soft !important;
    color: @primary-color !important;
  }
  
  :deep(.ant-table-tbody > tr:hover > td) {
    background-color: lighten(@primary-color-soft, 3%) !important;
  }
  
  :deep(.ant-table-tbody > tr.ant-table-row-selected > td) {
    background-color: @primary-color-soft !important;
  }
  
  :deep(.ant-table-thead > tr > th.ant-table-cell-fix-right) {
    background-color: @primary-color-soft !important;
  }
  
  .approve-btn {
    background-color: @primary-color;
    border-color: @primary-color;
  }
}

.action-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

// 批量审核按钮 - 青绿色系样式1
.batch-approve-btn {
  background: linear-gradient(135deg, @primary-color 0%, @primary-color-light 100%);
  border: none;
  color: #fff;
  border-radius: 0px;
  height: 40px;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(66, 139, 202, 0.35);
  
  &:hover:not(:disabled) {
    background: linear-gradient(135deg, @primary-color-dark 0%, @primary-color-light 100%);
    box-shadow: 0 4px 8px rgba(66, 139, 202, 0.4);
    transform: translateY(-1px);
  }
  
  &:disabled {
    background: @primary-color-muted;
    color: #fff;
    opacity:1;
  }
}

// 刷新按钮 - 青绿色系样式2
.refresh-btn {
  border-radius: 0px;
  height: 40px;
  font-size: 16px;
  background: linear-gradient(135deg, @primary-color 0%, @primary-color-light 100%);
  border: 1px solid @primary-color-soft;
  color: #ffffff;
  font-weight: 500;
  
  &:hover {
    background: linear-gradient(135deg, @primary-color-dark 0%, @primary-color-light 100%);
    border-color: @primary-color-light;
    color: white;
    border: 1px solid @primary-color-soft;
  }
}

// 下载Excel按钮 - 青绿色系样式3
.download-excel-btn {
  background: linear-gradient(135deg, @primary-color 0%, @primary-color-light 100%);
  border: none;
  color: #fff;
  font-size: 16px;
  height: 40px;
  border-radius: 0px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(66, 139, 202, 0.15);
  
  &:hover {
    background: linear-gradient(135deg, @primary-color-dark 0%, @primary-color-light 100%);
  }
}

// 通过审核按钮 - 三套青绿色系样式
.approve-btn {
  height: 36px;
  font-size: 16px;
  border-radius: 0px;
  min-width: 86px;
  border: none;
  font-weight: 500;
  transition: all 0.1s;
}

// 样式1：渐变青绿色
.approve-btn-style1 {
  background: linear-gradient(135deg, @primary-color 0%, @primary-color-light 100%);
  color: #fff;
  box-shadow: 0 2px 4px rgba(66, 139, 202, 0.3);
  
  &:hover {
    background: linear-gradient(135deg, @primary-color-dark 0%, @primary-color-light 100%);
    box-shadow: 0 4px 8px rgba(66, 139, 202, 0.4);
    transform: translateY(-1px);
  }
}

// 样式2：亮青绿色
.approve-btn-style2 {
  background: @primary-color;
  color: #fff;
  border: 1px solid @primary-color-light;
  
  &:hover {
    background: @primary-color-light;
    border-color: @primary-color-light;
    color: #fff;
    transform: translateY(-1px);
  }
}

// 样式3：深青绿色
.approve-btn-style3 {
  background: @primary-color;
  color: #fff;
  box-shadow: 0 2px 4px rgba(66, 139, 202, 0.35);
  
  &:hover {
    background: @primary-color-light;
    box-shadow: 0 4px 8px rgba(66, 139, 202, 0.45);
    transform: translateY(-1px);
  }
}

// 审核的表单
.search-form{
  font-size:17px;
  position: relative;
  left:220px;
}


// 不通过审核按钮样式
.reject-btn {
  height: 36px;
  font-size: 16px;
  border-radius: 0px;
  min-width: 100px;
  border: none;
  font-weight: 500;
  transition: all 0.1s;
  background: #ff4d4f;
  color: #fff;
  box-shadow: 0 2px 4px rgba(255, 77, 79, 0.3);
  
  &:hover {
    background: #ff7875;
    box-shadow: 0 4px 8px rgba(255, 77, 79, 0.45);
    transform: translateY(-1px);
    color: #fff;
  }
}

.drawer-reject-btn {
  min-width: 120px;
}

// 查看按钮样式 - 与通过审核按钮样式一致
.view-btn {
  height: 36px;
  font-size: 16px;
  border-radius: 0px;
  min-width: 86px;
  border: none;
  color: #fff;
  background: linear-gradient(135deg, @primary-color 0%, @primary-color-light 100%);
  font-weight: 500;
  transition: all 0.1s;
  box-shadow: 0 2px 4px rgba(66, 139, 202, 0.3);
  
  &:hover {
    color: white;
    background: linear-gradient(135deg, @primary-color-dark 0%, @primary-color-light 100%);
    box-shadow: 0 4px 8px rgba(66, 139, 202, 0.45);
    transform: translateY(-1px);
  }
}

.payment-proof-images {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
  max-width: 150px;
}

.payment-proof-img {
  cursor: pointer;
  transition: transform 0.2s;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid #e4e7ed;

  &:hover {
    transform: scale(1.15);
    border-color: @primary-color;
    box-shadow: 0 2px 8px fade(@primary-color, 35%);
  }
}
/* 首次/补考颜色高亮 */
.subject-name-cell {
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 4px;
  
  &.subject-first {
    color: #1890ff;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
  }
  
  &.subject-retake {
    color: #fa8c16;
    background-color: #fff7e6;
    border: 1px solid #ffd591;
  }
}

.registration-type-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 4px;
  font-weight: 600;
  font-size: 14px;
  
  &.type-first {
    color: #1890ff;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
  }
  
  &.type-retake {
    color: #fa8c16;
    background-color: #fff7e6;
    border: 1px solid #ffd591;
  }
}
</style>
